package com.sojson.config.datasource.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.sojson.aspect.PointcutsBase;
import com.sojson.config.datasource.annotation.DataSource;
import com.sojson.config.datasource.enums.EDataSourceType;
import com.sojson.constant.ConstantServlet;
import com.sojson.util.annotation.AnnoUtil;
import com.sojson.util.db.DbUtil;

/**
 * 多数据源处理
 *
 * @author lizl
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@Aspect
@Component
public class DataSourceAspect implements PointcutsBase {

    private static final String ANNO_PACKAGE_PATH =
        ConstantServlet.PACKAGE_DEFAULT_BASE + ".config.datasource.annotation";

    @Pointcut("@annotation(" + ANNO_PACKAGE_PATH + ".DataSource)" + "|| @within(" + ANNO_PACKAGE_PATH + ".DataSource)")
    public void pointCutAnno() {}

    /**
     * 基于注解切换数据源
     * 
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("pointCutAnno()")
    public Object pointCutAnno(ProceedingJoinPoint point) throws Throwable {
        // 获取注解
        DataSource dataSource = AnnoUtil.getAnnoByMethodAndClass(point, DataSource.class);
        EDataSourceType value = dataSource.value();

        DbUtil.push(value.toString());
        return point.proceed();
    }

}